package net.sshiffon;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;

public class KeepaliveManager implements Runnable {
	private static Logger logger = Logger.getLogger(KeepaliveManager.class);
	private final Session session;
	private final int intervalSeconds;
	private boolean run=true;
	
	public KeepaliveManager(Session session, int intervalSeconds)
	{
		this.session= session;
		this.intervalSeconds= intervalSeconds;
	}
	public void run()
	{
		run=true;
		try {
			//ChannelShell channel= null;
			while(run)
			{
				logger.debug("waiting for "+intervalSeconds+" seconds");
				Thread.sleep(intervalSeconds*1000);

				logger.debug("hoping to send a keepalive message (after "+intervalSeconds+")");
				if(session.isConnected())
				{
					logger.debug("sending a keepalive message");
					String command="#";
					 Channel channel=session.openChannel("exec");
				      ((ChannelExec)channel).setCommand(command);
				      channel.connect();
				      ((ChannelExec)channel).start();
				      channel.disconnect();
				} else {
					logger.debug("NOT sending a keepalive message");
					run=false;
					return;
				}
			}
		} catch (InterruptedException e) {
			logger.warn("Interrupted while sending keepalive",e);
		} catch (Throwable e) {
			logger.error("Exception while sending keepalive",e);
		}
	}
	
	public void stop()
	{
		run=false;
	}
}
